<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="queryParams.userType" placeholder="请选择用户类型" clearable size="small">
          <el-option
            v-for="dict in userTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>-->
      <el-form-item label="机构" prop="institutionId" v-if="admin">
        <el-select v-model="queryParams.deptId" filterable placeholder="请选择机构" clearable size="small" @change="selectClass">
          <el-option
            v-for="dept in deptList"
            :key="dept.institutionId"
            :label="dept.institutionName"
            :value="dept.institutionId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="classId" v-if="admin">
        <el-select v-model="queryParams.classId" placeholder="请选择班级" clearable size="small">
          <el-option
            v-for="dept in classList"
            :key="dept.classId"
            :label="dept.className"
            :value="dept.classId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="卡号" prop="icCard">
        <el-input
          v-model="queryParams.icCard"
          placeholder="请输入卡号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="personList" @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="55" align="center" />-->
      <!--<el-table-column label="用户ID主键" align="center" prop="personId" />-->
      <!--<el-table-column label="用户类型" align="center" prop="personType" :formatter="userTypeFormat" />-->
      <el-table-column label="学生名" align="center" prop="userName" />
      <el-table-column label="卡号" align="center" prop="icCard" />
      <el-table-column label="机构名称" align="center" prop="deptName" />
      <!--<el-table-column label="设备上的人员ID" align="center" prop="devicePersonId" />-->
      <!--<el-table-column label="年级ID" align="center" prop="gradeId" />-->
      <el-table-column label="年级名称" align="center" prop="gradeName" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="用户照片" align="center" prop="image" >
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.image"
            :preview-src-list='[scope.row.image]'>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tongban:person:edit']"
          >写卡</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="addPersonDevice(scope.row)"
            v-hasPermi="['tongban:person:remove']"
          >下发到设备</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备注册用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" @submit.native.prevent>
        <el-form-item label="卡号" prop="icCard">
          <el-input v-focus v-model="form.icCard" placeholder="请录入卡号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPerson, getPerson, delPerson, addPerson, updatePerson, exportPerson, devolutionPerson } from "@/api/tongban/person";
import { listInstitutionData } from "@/api/tongban/institution";
import { listInstitutionClass } from "@/api/tongban/class";
import { getInfo } from '@/api/login'
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "Person",
  components: {
    ImageUpload,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      authentication: 0, //0=key A模式,4=key B模式
      nums: 0, //错误次数
      // 总条数
      total: 0,
      deptList: [],
      classList: [],
      userTypeOptions:[],
      // 设备注册用户表格数据
      personList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      admin: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personType: null,
        deptId: null,
        deptName: null,
        devicePersonId: null,
        gradeId: null,
        gradeName: null,
        classId: null,
        className: null,
        image: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        devicePersonId: [
          { required: true, message: "设备上的人员ID不能为空", trigger: "blur" }
        ],
      }
    };
  },
  directives: {
    focus: {
      update: function (el) {
        //console.log(el);
        //因为el-input这是个组件，input外面被一层 div 包裹着
        //el打印出来是外面这个 div，需要找到内层的input
        el.children[0].focus();
      },
      inserted: function (el) {
        //console.log(el);
        //因为el-input这是个组件，input外面被一层 div 包裹着
        //el打印出来是外面这个 div，需要找到内层的input
        el.children[0].focus();
      }
    }
  },
  created() {
    this.getList();
    this.getDicts("user_type").then(response => {
      this.userTypeOptions = response.data;
    });
    listInstitutionData().then(res => {
      this.deptList = res.data;
    })
    this.isAdmin();
  },
  methods: {
    /** 查询设备注册用户列表 */
    getList() {
      this.loading = true;
      listPerson(this.queryParams).then(response => {
        this.personList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    isAdmin(){
      getInfo().then(response => {
        if(response.user.userId == 1){
          this.admin = true;
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        personId: null,
        personType: null,
        deptId: null,
        deptName: null,
        devicePersonId: null,
        gradeId: null,
        gradeName: null,
        classId: null,
        className: null,
        image: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    addPersonDevice(row) {
      devolutionPerson(row.personId).then(res =>{
        console.log(res.data);
      });
    },
    selectClass(id){
      listInstitutionClass(id).then(res => {
        this.classList = res.data;
        //this.form.classId = this.classList[0];
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.personId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    userTypeFormat(row) {
      return this.selectDictLabel(this.userTypeOptions, row.personType);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备注册用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const personId = row.personId || this.ids
      getPerson(personId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "写卡";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.personId != null) {
            updatePerson(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPerson(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const personIds = row.personId || this.ids;
      this.$confirm('是否确认删除设备注册用户编号为"' + personIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPerson(personIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有设备注册用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPerson(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
